package com.xbjtech.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.xbjtech.model.User;
import com.xbjtech.service.UserService;
import com.xbjtech.util.AppConfig;

@Controller
public class LoginController {
	
	@Autowired
	UserService userService;
	
	@GetMapping("/login")
	public String login() {
		return "login";
	}
	
	@PostMapping("/login")
	public String login(HttpServletRequest request, @RequestParam String username, @RequestParam String password, Model model) {
		User user = userService.login(username, DigestUtils.md5Hex(password));
		if (user == null) {
			//登录失败
			model.addAttribute("errorMessage", "用户名密码不正确!");
			return "login";
		} else {
			//登录成功
			request.getSession().setAttribute(AppConfig.LOGIN_USER_SESSION, user);
			user.setLastloginip(request.getRemoteAddr());
			user.setLastlogintime(new Date());
			userService.update(user);
		}
		return "redirect:admin/index";
	}
	
	@GetMapping("/logout")
	public String logout(HttpSession session) {
		session.removeAttribute(AppConfig.LOGIN_USER_SESSION);
		return "redirect:/";
	}
}
